package com.ycit.org.client.rpcClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.stream.Stream;

import org.apache.log4j.Logger;

import com.ycit.org.rpc.SocketRpc;

public class Client {

	WorkerSocket socket;
	private static final Logger logger = Logger.getLogger(Client.class);
	private static final byte RPCMETHODCALL = 0B00000001;
	private static final byte RPCOBJECT = 0B00000010;

	public Client() {
		socket = WorkerSocket.getInstance();
	}

	private void send(byte[] bt) {
		socket.write(bt, null);
	}

	private void receive(byte[] bt) {
		socket.read(bt, null);
	}

	public static class WorkerSocket implements SocketRpc {

		Socket clientSocket;
		InputStream in;
		OutputStream out;

		private WorkerSocket() {
			try {
				clientSocket = new Socket("localhost", 520);
				out = clientSocket.getOutputStream();
				System.out.println(out);
				in = clientSocket.getInputStream();
				System.out.println(in);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public static WorkerSocket getInstance() {
			return new WorkerSocket();
		}

		@Override
		public void send(byte[] bt, OutputStream stream) {
			// TODO Auto-generated method stub
			write(bt, null);
		}

		@Override
		public void receive(byte[] bt, InputStream stream) {
			// TODO Auto-generated method stub
			read(bt, null);
		}

		@Override
		public void write(byte[] bt, OutputStream stream) {
			// TODO Auto-generated method stub
			try {
				out.write(bt);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
				logger.error("");
			}
			finally{
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		@Override
		public void read(byte[] bt, InputStream stream) {
			// TODO Auto-generated method stub
			try {
				in.read(bt);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		Client client = new Client();
		while(true){
		client.send("zhummm".getBytes());
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
}
